package com.ibpd.henuocms.web.controller.manage;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.ibpd.henuocms.common.IbpdCommon;
import com.ibpd.henuocms.entity.SystemProperEntity;
import com.ibpd.henuocms.service.SystemProper.ISystemProperService;
import com.ibpd.henuocms.service.SystemProper.SystemProperServiceImpl;

@Controller
public class SysProper extends BaseController {
	@RequestMapping("Manage/SysProper/index.do")
	public String index(Model model) throws IOException{
		model.addAttribute(PAGE_TITLE,"系统参数设置");
		ISystemProperService propServ=(ISystemProperService) getService(SystemProperServiceImpl.class);
		List<SystemProperEntity> list=propServ.getList();
		
		Map<String,String> kvMap=new HashMap<String,String>();
		for(SystemProperEntity p:list){
			kvMap.put(p.getDisplayName(), getValue(p));
		}
		model.addAttribute("map",kvMap);
		return "manage/sysProper/index";
	}	
	private String getValue(SystemProperEntity p){
		if(p==null)
			return null;
		if(p.getDataType().trim().toLowerCase().equals("string")){
			return "<input type=\"text\" name=\""+p.getKeyName()+"\" mthod=\"smt\" value=\""+(p.getValue()==null || p.getValue().trim().length()==0?p.getDefaultValue():p.getValue().trim())+"\"/>";
		}else if(p.getDataType().trim().toLowerCase().equals("boolean")){
			String[] vs=p.getDefaultValue().split(";");
			String v=p.getValue();
			String r="<select  name=\""+p.getKeyName()+"\" mthod=\"smt\">\r\n";
			for(String s:vs){
				String[] ss=s.split(":");
				r+="\t<option value=\""+ss[1]+"\""+(v.toLowerCase().trim().equals(ss[1].trim().toLowerCase())?" selected ":"")+">"+ss[0]+"</option>\r\n";
			}
			r+="</select>\r\n";
			return r;
		}else{
			p.setDataType("string");
			return getValue(p);
		}
	}
	@RequestMapping("Manage/SysProper/doUpdate.do")
	public void doUpdate(HttpServletRequest req,HttpServletResponse resp,String key,String value) throws IOException{
		if(StringUtils.isBlank(key) || StringUtils.isBlank(value)){
			printParamErrorMsg(resp);
			return;
		}
		ISystemProperService propServ=(ISystemProperService) getService(SystemProperServiceImpl.class);
		propServ.saveProperByKeyValue(key, value);
		IbpdCommon.resetSysPropertiesCache();
		super.printMsg(resp, "99", "99", "保存成功");
	}
}
